import Mock from 'mockjs'

// 确保正确设置MockJS
Mock.setup({
  timeout: '300-600'
})

// 存储模拟用户数据
let users = []
for (let i = 1; i <= 45; i++) {
  users.push(Mock.mock({
    id: i,
    username: '@word(5, 10)',
    name: '@cname()',
    email: '@email()',
    role: '@pick(["管理员", "普通用户"])',
    status: '@pick(["active", "inactive"])',
    createdAt: '@datetime',
    updatedAt: '@datetime'
  }))
}

// 登录接口
Mock.mock(/\/api\/login/, 'post', options => {
  console.log('MockJS收到登录请求:', options)
  
  try {
    const { username, password } = JSON.parse(options.body)
    console.log('解析后的登录参数:', { username, password })
    
    // 模拟登录验证
    if (!username || !password) {
      // 参数缺失
      console.log('登录参数缺失')
      return {
        code: 400,
        data: null,
        message: '用户名和密码不能为空'
      }
    } else if (username === 'admin' && password === '123456') {
      // 登录成功
      console.log('管理员登录成功')
      return {
        code: 200,
        data: {
          token: Mock.Random.string('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 32),
          userInfo: {
            id: Mock.Random.guid(),
            username: 'admin',
            name: '管理员',
            email: 'admin@example.com'
          }
        },
        message: '登录成功'
      }
    } else if (username === 'user' && password === '123456') {
      // 普通用户登录成功
      console.log('普通用户登录成功')
      return {
        code: 200,
        data: {
          token: Mock.Random.string('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 32),
          userInfo: {
            id: Mock.Random.guid(),
            username: 'user',
            name: '普通用户',
            email: 'user@example.com'
          }
        },
        message: '登录成功'
      }
    } else if (username === 'error') {
      // 模拟服务器内部错误
      console.log('模拟服务器内部错误')
      return {
        code: 500,
        data: null,
        message: '服务器内部错误'
      }
    } else {
      // 用户名或密码错误
      console.log('用户名或密码错误')
      return {
        code: 401,
        data: null,
        message: '用户名或密码错误'
      }
    }
  } catch (error) {
    console.error('解析登录请求体时出错:', error)
    return {
      code: 500,
      data: null,
      message: '服务器内部错误'
    }
  }
})

// 获取用户列表（分页）
Mock.mock(/\/api\/users/, 'get', options => {
  const params = new URLSearchParams(options.url.split('?')[1])
  const page = parseInt(params.get('page')) || 1
  const size = parseInt(params.get('size')) || 10
  const username = params.get('username') || ''  // 获取用户名查询参数
  
  // 过滤用户数据
  let filteredUsers = users
  if (username) {
    filteredUsers = users.filter(user => 
      user.username.toLowerCase().includes(username.toLowerCase())
    )
  }
  
  const start = (page - 1) * size
  const end = start + size
  const pageUsers = filteredUsers.slice(start, end)
  
  return {
    code: 200,
    data: {
      users: pageUsers,
      total: filteredUsers.length,  // 返回过滤后的总数
      page,
      size
    },
    message: '获取用户列表成功'
  }
})

// 获取用户详情
Mock.mock(/\/api\/users\/\d+/, 'get', options => {
  const urlParts = options.url.split('/')
  const id = parseInt(urlParts[urlParts.length - 1])
  
  const user = users.find(u => u.id === id)
  
  if (user) {
    return {
      code: 200,
      data: user,
      message: '获取用户详情成功'
    }
  } else {
    return {
      code: 404,
      data: null,
      message: '用户不存在'
    }
  }
})

// 创建用户
Mock.mock(/\/api\/users/, 'post', options => {
  const userData = JSON.parse(options.body)
  
  // 检查用户名是否已存在
  const existingUser = users.find(u => u.username === userData.username)
  if (existingUser) {
    return {
      code: 400,
      data: null,
      message: '用户名已存在'
    }
  }
  
  const newUser = Mock.mock({
    id: users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1,
    username: userData.username,
    name: userData.name,
    email: userData.email,
    role: userData.role,
    status: userData.status,
    createdAt: '@datetime',
    updatedAt: '@datetime'
  })
  
  users.push(newUser)
  
  return {
    code: 200,
    data: newUser,
    message: '创建用户成功'
  }
})

// 更新用户
Mock.mock(/\/api\/users\/\d+/, 'put', options => {
  const urlParts = options.url.split('/')
  const id = parseInt(urlParts[urlParts.length - 1])
  const userData = JSON.parse(options.body)
  
  const index = users.findIndex(u => u.id === id)
  
  if (index !== -1) {
    // 检查用户名是否已存在（排除当前用户）
    const existingUser = users.find(u => u.username === userData.username && u.id !== id)
    if (existingUser) {
      return {
        code: 400,
        data: null,
        message: '用户名已存在'
      }
    }
    
    users[index] = {
      ...users[index],
      ...userData,
      updatedAt: Mock.mock('@datetime')
    }
    
    return {
      code: 200,
      data: users[index],
      message: '更新用户成功'
    }
  } else {
    return {
      code: 404,
      data: null,
      message: '用户不存在'
    }
  }
})

// 删除用户
Mock.mock(/\/api\/users\/\d+/, 'delete', options => {
  const urlParts = options.url.split('/')
  const id = parseInt(urlParts[urlParts.length - 1])
  
  const index = users.findIndex(u => u.id === id)
  
  if (index !== -1) {
    users.splice(index, 1)
    
    return {
      code: 200,
      data: null,
      message: '删除用户成功'
    }
  } else {
    return {
      code: 404,
      data: null,
      message: '用户不存在'
    }
  }
})

export default Mock